package com.gg.ai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gg.ai.mapper.ChatHistoryMapper;
import com.gg.ai.pojo.ChatHistory;
import com.gg.ai.pojo.JsonVariable;
import com.gg.ai.pojo.TextDTO;
import com.gg.ai.service.ChatHistoryService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Reader;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ChatHistoryServiceImpl implements ChatHistoryService {
    @Autowired
    private ChatHistoryMapper chatHistoryMapper;

    private final Gson gson = new Gson();
    @Override
    public ChatHistory queryList(Integer userId,String sessionId) {
        QueryWrapper<ChatHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId).eq("session_id",sessionId);
        return chatHistoryMapper.selectOne(queryWrapper);
    }

    @Override
    public ChatHistory getSessionById(Integer id) {

        return chatHistoryMapper.selectById(id) != null?  chatHistoryMapper.selectById(id) : null;
    }

    @Override
//    List<Map<String,Object>> historyList
        public boolean updateHistoryList(Integer id, List<Map<String,Object>> historyList) {

        ChatHistory chatHistory = new ChatHistory();
        String json = gson.toJson(historyList);
        System.out.println(json);
//        chatHistory.setHistoryList(historyList);
        System.out.println(chatHistory.getHistoryList());

        QueryWrapper<ChatHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        return chatHistoryMapper.update(chatHistory,queryWrapper) >= 1;
    }

    public List<ChatHistory> getSessionByUserId(Integer userId) {
        QueryWrapper<ChatHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId).orderByDesc("update_time");
        return chatHistoryMapper.selectList(queryWrapper);
    }

    public  boolean insertSession(Integer userId) {
        ChatHistory chatHistory = new ChatHistory();
        List<ChatHistory> sessionByUserId = getSessionByUserId(userId);
        chatHistory.setSessionId((long) sessionByUserId.size());
        chatHistory.setHistoryList("[]");
        chatHistory.setCreateTime(LocalDateTime.now());
        chatHistory.setUserId(userId);
        chatHistory.setUpdateTime(LocalDateTime.now());

        return  chatHistoryMapper.insert(chatHistory) >= 1;
    }

    public boolean deleteSession(Integer id) {
       return chatHistoryMapper.deleteById(id) >= 1;
    }
}
